// pages/feedback/feedback.js
const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    info: {
      description: '',
      imgPath: ''
    },
    imgSrc: '',
    disabled: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  uploadImage () {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album'],
      success: (result)=>{
        this.setData({
          imgSrc: result.tempFilePaths[0]
        });
        
        let type = '';
        this.data.imgSrc && (type = this.data.imgSrc.slice(this.data.imgSrc.lastIndexOf('.')));

        // 文件上传
        wx.cloud.uploadFile({
          cloudPath: app.methods.formatTime('YYYY-MM-DD HH:MM:SS') + type,
          filePath: result.tempFilePaths[0],
          success: res => {
            this.setData({
              'info.imgPath': res.fileID
            });
          },
          fail: err => {
            wx.showModal({
              title: '错误提示',
              content: '图片上传失败！' + err,
              showCancel: true
            });
          }
        });

      },
      fail: ()=>{
        wx.showModal({
          title: '错误提示',
          content: '无法打开本地相册！',
          showCancel: true
        });
      }
    });
  },

  handleInput (e) {
    const text = e.detail.value;
    this.setData({
      'info.description': text
    });
  },

  submitInfo () {
    wx.vibrateShort({
      type: 'heavy'
    });

    if (this.data.info.description.trim()) {
      // 禁止重复提交
      this.setData({
        disabled: true
      });

      wx.cloud.callFunction({
        name: 'feedback',
        data: {
          info: this.data.info
        }
      }).then(res => {
        wx.showToast({
          title: '提交成功！',
          icon: 'success',
          duration: 2500,
          success: (result)=>{
            this.setData({
              info: {
                description: '',
                imgPath: ''
              },
              imgSrc: ''
            });
          }
        });
      }).catch(e => {
        wx.showModal({
          title: '错误提示',
          content: '意见提交失败！' + e,
          showCancel: true
        });
      }).finally(() => {
        this.setData({
          disabled: false
        });
      });
    } else {
      wx.showModal({
        title: '提交内容缺失',
        content: '问题和意见为必填内容！',
        showCancel: true
      });
    }
  }
})